<template>
  <div class="login" >
    <div style="margin-top: 100%">
      <a-form
        ref="formLogin"
        id="formLogin"
        :form="form"
        class="login-form" >
        <h1 class="title" style="font-weight:900">健康体检管理系统</h1>
        <a-form-item >
          <a-input
            size="large"
            type="text"
            placeholder="请输入您的用户名"
            v-decorator="['login',{rules: [{ required: true, message: '请输入帐户名或邮箱地址' }, { validator: handleUsernameOrEmail }], validateTrigger: 'change'}]"
          >
            <a-icon slot="prefix" type="user" :style="{ color: 'rgba(80,145,230,0.8)' }"/>
          </a-input>
        </a-form-item>
        <a-form-item >
          <a-input
            size="large"
            type="password"
            autocomplete="false"
            placeholder="请输入密码"
            v-decorator="['passwd',{rules: [{ required: true, message: '请输入密码' }], validateTrigger: 'blur'}]"
          >
            <a-icon slot="prefix" type="lock" :style="{ color: 'rgba(80,145,230,0.8)' }"/>
          </a-input>
        </a-form-item>
        <a-row :gutter="0">
          <a-col :span="16">
            <a-form-item >
              <a-input
                size="large"
                type="text"
                placeholder="请输入验证码"
                v-decorator="['inputCode',{rules: [{ required: true, message: '请输入验证码' }],validateTrigger: 'blur'}]" >
              </a-input>
            </a-form-item>
          </a-col>
          <a-col :span="8" style="text-align: right">
            <img
              v-if="requestCodeSuccess"
              style="margin-top: 2px;"
              :src="randCodeImage"
              @click="handleChangeCheckCode"/>
            <img
              v-else
              style="margin-top: 2px;"
              src="../../assets/checkcode.png"
              @click="handleChangeCheckCode"/>
          </a-col>
        </a-row>
        <a-form-item layout="inline" style="margin-top: -15px;">
          <a-checkbox v-decorator="['rememberMe', {initialValue: true, valuePropName: 'checked'}]" style="color:rgba(80,145,230,0.8)">
            记住密码
          </a-checkbox>

        </a-form-item>

        <a-form-item style="margin-top: -15px;">
          <a-button
            size="large"
            type="primary"
            htmlType="submit"
            style="width:100%;"
            @click.stop.prevent="handleSubmit"
            :style="{ fontSize: '18px',height:'40px'}"
          >登录
          </a-button>
        </a-form-item>
      </a-form>
    </div>
  </div>
</template>

<script>
import md5 from 'md5'
import TwoStepCaptcha from '@/components/tools/TwoStepCaptcha'
import { mapActions } from 'vuex'
import { timeFix } from '@/utils/util'
import { getAction } from '@/api/manage'
export default {
  components: {
    TwoStepCaptcha
  },
  data () {
    return {
      inputCode: '',
      randCodeImage: '',
      requestCodeSuccess: false,
      titylogoStyle: {
        backgroundImage: 'url(' + require('@/assets/tinylogo.png') + ')',
        backgroundRepeat: 'no-repeat',
        backgroundSize: '100% auto'
      },
      customActiveKey: 'tab1',
      loginBtn: false,
      // login type: 0 email, 1 username, 2 telephone
      loginType: 0,
      isLoginError: false,
      requiredTwoStepCaptcha: false,
      stepCaptchaVisible: false,
      form: this.$form.createForm(this),
      state: {
        time: 60,
        loginBtn: false,
        // login type: 0 email, 1 username, 2 telephone
        loginType: 0,
        smsSendBtn: false
      }
    }
  },
  created () {
    this.handleChangeCheckCode()
  },
  methods: {
    ...mapActions(['Login', 'Logout']),
    // handler
    handleUsernameOrEmail (rule, value, callback) {
      const { state } = this
      const regex = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+((\.[a-zA-Z0-9_-]{2,3}){1,2})$/
      if (regex.test(value)) {
        state.loginType = 0
      } else {
        state.loginType = 1
      }
      callback()
    },
    handleChangeCheckCode () {
      this.currdatetime = new Date().getTime()
      this.inputCode = ''
      getAction(`/system/auth/randomImage/${this.currdatetime}`).then(res => {
        // eslint-disable-next-line eqeqeq
        if (res.code == '0000') {
          this.randCodeImage = res.result.result
          this.requestCodeSuccess = true
        } else {
          this.$message.error(res.message)
          this.requestCodeSuccess = false
        }
      }).catch(() => {
        this.requestCodeSuccess = false
      })
    },
    handleSubmit (e) {
      e.preventDefault()
      const {
        state,
        Login
      } = this

      state.loginBtn = true
      this.form.validateFields(['login', 'passwd', 'inputCode'], { force: true }, (err, values) => {
        if (!err) {
          const loginParams = { ...values, checkKey: this.currdatetime }
          console.log('loginParams', loginParams)
          delete loginParams.login
          loginParams[!state.loginType ? 'email' : 'login'] = values.login
          loginParams.passwd = md5(values.passwd)
          Login(loginParams)
              .then((res) => {
                  this.loginSuccess(res)
              },(errors) => {
                  console.log(errors)
                  this.handleChangeCheckCode()
              })
              .finally(() => {
                state.loginBtn = false
              })
        } else {
          setTimeout(() => {
            state.loginBtn = false
          }, 600)
        }
      })
    },
    getCaptcha (e) {},
    stepCaptchaSuccess () {
      this.loginSuccess()
    },
    stepCaptchaCancel () {
      this.Logout().then(() => {
        this.loginBtn = false
        this.stepCaptchaVisible = false
      })
    },
    loginSuccess (res) {
      this.$router.push({ path: '/' })
      // 延迟 1 秒显示欢迎信息
      setTimeout(() => {
        this.$notification.success({
          message: '欢迎',
          description: `${timeFix()}，欢迎回来`
        })
      }, 1000)
      this.isLoginError = false
    }
  }
}
</script>

<style lang="less" scoped>
.title {
  margin: 0px auto 30px auto;
  text-align: center;
  color: #707070;
}
.login {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
}
.login-form {
  border-radius: 6px;
  background: #ffffff;
  width: 400px;
  padding: 25px 25px 5px 25px;
  .el-input {
    height: 38px;
    input {
      height: 38px;
    }
  }
  .input-icon {
    height: 39px;
    width: 14px;
    margin-left: 2px;
  }
}
.login-tip {
  font-size: 13px;
  text-align: center;
  color: #bfbfbf;
}
.login-code {
  width: 33%;
  height: 38px;
  float: right;
  img {
    cursor: pointer;
    vertical-align: middle;
  }
}
.login-code-img {
  height: 38px;
}
.ant-form-item {
  box-sizing: border-box;
  margin: 0;
  padding: 0;
  line-height: 38px !important;
  height: 38px !important;
  color: rgba(0, 0, 0, 0.65);
  font-variant: tabular-nums;
  list-style: none;
  font-feature-settings: 'tnum';
  vertical-align: top;
  margin-bottom: 20px !important;
}
</style>
